<?php
/**
 * Created by PhpStorm.
 * User: sosyuki
 * Date: 2018-12-07
 * Time: 15:01
 */

namespace Drupal\points\Entity;


use Entity;

class Points extends Entity {

  public $id;

  public $type;

  public $description;

  public $point;

  public $total;

  public $total_point;

  public $uid;

  public $op_uid;

  public $updated;

  public $created;

  protected $only_update = FALSE;

  function __construct($values = []) {
    if (isset($values['type']) && is_object($values['type'])) {
      $values['type'] = $values['type']->type;
    }
    parent::__construct($values, 'points');
  }


  function total_point() {
    return points_get_total($this->uid, $this->type);
  }

  public function label() {
    return "{$this->id} {$this->point}";
  }

  function getOnlyUpdate() {
    return $this->only_update;
  }

  function setOnlyUpdate(bool $only_update) {
    $this->only_update = $only_update;
    return $this;
  }

  function save() {
    $this->op_uid = $GLOBALS['user']->uid;
    //0 不记录
    if ($this->point == 0) {
      return;
    }
    //uid 0 匿名用户 积分不记录
    if ($this->uid == 0) {
      return;
    }
    $this->updated = REQUEST_TIME;
    if (!isset($this->created)) {
      $this->created = REQUEST_TIME;
    }
    if (!isset($this->uid)) {
      global $user;
      $this->uid = $user->uid;
    }

    if (!$this->only_update) {
      points_change_total($this->uid, $this->type, $this->point);
    }
    //记录历史结余
    $this->total = points_get_total($this->uid, $this->type);

    parent::save();

    return $this;
  }
}
